package com.tz.system.role.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tz.platform.common.CacheConstans;
import com.tz.platform.page.PageCondition;
import com.tz.platform.utils.ReturnUtil;
import com.tz.platform.utils.StringUtil;
import com.tz.system.cache.service.ParameterCache;
import com.tz.system.menu.model.TSysMenu;
import com.tz.system.menu.service.TSysMenuService;
import com.tz.system.role.dao.TMgtRoleDao;
import com.tz.system.role.model.TMgtRole;
import com.tz.system.role.model.TMgtRolePrivate;
import com.tz.system.role.service.RolePrivateService;
import com.tz.system.role.service.TMgtRoleService;

@Service("tMgtRoleServiceImpl")
@Transactional
public  class TMgtRoleServiceImpl implements TMgtRoleService {

	@Autowired
	private ParameterCache parameterCache;   //加载缓存
	
	@Autowired
	private RolePrivateService rolePrivateService;
	
	@Autowired
	private TSysMenuService tSysMenuService;
	
	@Autowired
	private TMgtRoleDao tMgtRoleDao;
	
	//查询分页
	private static final String queryPageTMgtRoleHql = " from TMgtRole ";
	
	private static final String queryByRoleCodeHql = " from TMgtRole where roleCode=?";
	
	@Override
	@Transactional
	public PageCondition findByPage(PageCondition condition) {
		condition = tMgtRoleDao.findByPage(queryPageTMgtRoleHql, condition);
		return condition;
	}
	
	
	@Override
	@Transactional
	public Map<String,Object> removeById(Integer id) {
		try {
			TMgtRole entity = queryById(id);
			tMgtRoleDao.removeById(id);
			//删除角色配置的菜单
			rolePrivateService.removePrivateByRoleCode(entity.getRoleCode());
			//加载所有的缓存
			parameterCache.deleteRedis(CacheConstans.ROLES, entity.getRoleCode());
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "删除失败！");
		}
		return ReturnUtil.returnMessage("success", "删除成功！");
	}
	
	@Override
	@Transactional
	public Map<String,Object> addSave(TMgtRole entity) {
		//1、检查用户id是否重复
		try {
			TMgtRole tRole = this.queryByRoleCode(entity.getRoleCode());
			if(tRole!=null){
				return ReturnUtil.returnMessage("fail", "角色编号重复");	
			}
			tMgtRoleDao.save(entity);
			//加载redis缓存
			parameterCache.loadRedis(CacheConstans.ROLES , entity.getRoleCode(), entity);
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "添加失败！");
		}
		return ReturnUtil.returnMessage("success", "添加成功！");
	}
	
	@Override
	@Transactional
	public Map<String,Object> updateSave(TMgtRole entity) {
		try {
			tMgtRoleDao.saveOrUpdate(entity);
			//加载redis缓存
			parameterCache.loadRedis(CacheConstans.ROLES, entity.getRoleCode(), entity);
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnUtil.returnMessage("fail", "修改失败！");
		}
		return ReturnUtil.returnMessage("success", "修改成功！");
	}
	
	@Override
	@Transactional
	public TMgtRole queryById(Integer id) {
		return tMgtRoleDao.get(id);
	}
	
	@Override
	@Transactional
	public TMgtRole queryByRoleCode(String roleCode) {
		List<TMgtRole> roles = tMgtRoleDao.find(queryByRoleCodeHql, roleCode);
		if (roles != null && roles.size() > 0)
			return roles.get(0);
		else
			return null;
	}
	
	@Override
	@Transactional
	public List<TMgtRole> queryAll() {
		return tMgtRoleDao.getAll();
	}


	@Override
	public Map<String,Object> saveRolePrivates(String roleCode,String menusStr) {
		String message = "error";
		try {
			List<TMgtRolePrivate> rolePrivateList = rolePrivateService.getListByRoleCode(roleCode);
			List<Integer> removeIds=new ArrayList<Integer>();
			List<String> stillList=new ArrayList<String>();
			if(rolePrivateList!=null && rolePrivateList.size()>0){
				for(TMgtRolePrivate t :rolePrivateList){
					//是否是旧的功能
					boolean flag = false;
					for(String x: menusStr.split(",")){
						if(!StringUtil.msIsEmpty(x)){
							String tMCode = x.split("_")[1];
							String tMcodeP = tMCode.toString().substring(0,tMCode.toString().length()/2);
							if(t.getMenuCode().equals(tMCode) || t.getMenuCode().equals(tMcodeP)){
								flag = true;
								stillList.add(x);
								break;
							}
						}
					}
					//如果是已经去掉的功能，进入删除列表
					if(!flag){
						removeIds.add(t.getId());
					}
					
				}
			}
			//删除去除的功能
			if(removeIds!=null && removeIds.size()>0){
				rolePrivateService.removeRpByIdList(removeIds);
				//删除没有菜单的父级菜单
				for(Integer it : removeIds){
					String tMcodeP = it.toString().substring(0,it.toString().length()/2);
					boolean flag = rolePrivateService.checkSonExists(roleCode, tMcodeP);
					if(!flag){
						rolePrivateService.removeRolePrivate(roleCode, tMcodeP);
					}
				}
			}
			for(String x:menusStr.split(",")){
				if(!StringUtil.msIsEmpty(x)){
					String tMCode = x.split("_")[1];
					//如果是新的功能，则插入
					if(stillList !=null && !stillList.contains(x)){
						TMgtRolePrivate entity = new TMgtRolePrivate();
						entity.setRoleCode(roleCode);
						entity.setMenuCode(tMCode);
						rolePrivateService.saveRolePrivate(entity);
						
						//查看是否存在父级菜单的角色配置
						String pMcode = tMCode.substring(0,tMCode.length()/2);
						TMgtRolePrivate isRolePrivate = rolePrivateService.checkExists(roleCode, pMcode);
						if(isRolePrivate==null || isRolePrivate.getId()==0){
							TMgtRolePrivate entityP = new TMgtRolePrivate();
							entityP.setRoleCode(roleCode);
							entityP.setMenuCode(pMcode);
							rolePrivateService.saveRolePrivate(entityP);
						}
						
					}
				}
			}
			List<TSysMenu> list = tSysMenuService.getMenusByRoleCode(roleCode);
			//加载缓存
			parameterCache.loadRedis(CacheConstans.ROLEMENUS, roleCode, list);
			
			message = "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		if("success".equals(message)){
			return ReturnUtil.returnMessage(message, "保存成功");
		}
		return ReturnUtil.returnMessage(message, "保存失败");
	}

}

